<template>
  <j-modal :title="title" :width="width" :visible="visible" :confirmLoading="confirmLoading" :maskClosable="false"
    :keyboard="false" :forceRender="true" v-bind:prefixNo="prefixNo" switchHelp switchFullscreen @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp" :id="prefixNo" style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{ $t('inPrint.cancel') }}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{ $t('commodityManagement.preservation') }}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.customer')">
              <a-select :placeholder="$t('manuManagement.selectCustomer')" v-decorator="[ 'organId', validatorRules.organId ]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addCustomer"><a-icon type="plus" /> {{$t('popup.newCustomers')}}</div>
                </div>
                <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <!-- 关联订单 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.relatedOrder')" data-step="3"
              :data-title="$t('popup.relatedOrder')" :data-intro="$t('popup.purchaseReceiptAfterOrder')">
              <a-input-search :placeholder="$t('popup.pleaseSelectAssociated')" v-decorator="['number',validatorRules.number]"
                @search="onSearchLinkNumber" :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 单据日期 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.operTime]" :show-time="true" />
            </a-form-item>
          </a-col>
          <!-- 单据编号 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')"
              data-step="2" :data-title="$t('setailManagement.documentNo')"
              :data-intro="$t('popup.theNumberIsGenerated')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['billNo',validatorRules.billNo]" disabled
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :label="$t('manuManagement.advancePaySubstract')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select :disabled="!form.getFieldValue('organId')" :placeholder="$t('manuManagement.isAdvanceReceivedSubstract')" @change="selectMoneyChange" v-decorator.trim="['deduction']">
                    <a-select-option :value="1">{{ $t('reportQuery.yes') }}</a-select-option>
                    <a-select-option :value="0">{{ $t('reportQuery.no') }}</a-select-option>
                  </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.arrivalDate')">
              <j-date v-decorator="['arrivalTime']" :show-time="true"
                :placeholder="$t('otherJS.pleaseSelectTheArrDate')" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.deliveryMethod')">
              <a-input :placeholder="$t('otherJS.pleaseEnterDeliveryMethod')" v-decorator.trim="['deliveryMethod']" />
            </a-form-item>
          </a-col> -->
        </a-row>
        <!-- 表头结束 -->
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" >
              <span>{{$t('popup.documentRemark')}}：</span>
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['remark']"
                style="margin-top:8px;width: 88%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table id="billModal" :ref="refKeys[0]" :loading="materialTable.loading"
          :columns="materialTable.columns" :dataSource="materialTable.dataSource" :minWidth="minWidth" :maxHeight="300"
          :rowNumber="false" :rowSelection="rowCanEdit" :actionButton="rowCanEdit" :dragSort="false"
          @valueChange="barCodeValueChange" @inputPurchaseValueChange="onValueChange" @added="onAdded"
          @deleted="onDeleted">
          <template #buttonAfter>
            <a-row v-if="rowCanEdit" :gutter="24" style="float:left;padding-bottom: 5px;" data-step="4"
              :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">{{ $t('popup.codeScanningEntry') }}</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">
                <a-input :placeholder="$t('popup.pleaseScanBarcode')" v-model="scanBarCode" @pressEnter="scanPressEnter"
                  ref="scanBarCode" />
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px">
                <a-button @click="stopScan">{{ $t('popup.stowScanningCode') }}</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;padding-bottom: 5px;">
              <a-col :md="24" :sm="24">
                <a-button style="margin-left: 8px" @click="handleHistoryBillList"><a-icon type="history" />{{
                    $t('popup.historicalDocuments')
                }}</a-button>
              </a-col>
            </a-row>
          </template>
          <template #delete="record">
            <div style="text-align: center;">
              <a-popconfirm :title="$t('manuManagement.areDelete')"
                @confirm="() => removeRows(record)">
                <a-icon type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </template>
          <template #rowIndex="record">
            <div style="text-align: center;">{{ record.index + 1 }}</div>
          </template>
          <template #defaultNumber="record">
            <a @click="openBillDetail(record.value, '厂家到货')">{{record.value}}</a>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24" style="visibility: hidden;height: 0">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.amountAfter')" data-step="7"
              :data-title="$t('inPrint.amountAfter')" :data-intro="$t('popup.amountAmountGoodsIn')">
              <a-input :placeholder="$t('popup.pleaseEnterAfterDiscount')" v-decorator.trim="['totalPrice']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.collectionAccount')">
              <a-select style="width:185px;" :placeholder="$t('popup.pleaseSelectAccount')"
                v-decorator="['accountId',validatorRules.accountId]" :dropdownMatchSelectWidth="false" allowClear @select="selectAccount" @change="onSelectAccount">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addAccount"><a-icon type="plus" /> {{ $t('popup.newAccount') }}</div>
                </div>
                <a-select-option v-for="(item, index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-if="showCheckNumber" :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.checkNumber')">
              <a-input v-decorator.trim="[ 'taxInvoiceNo' ]" :placeholder="$t('financialManagement.pleaseEnterCheckNumber')" />
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.deposit')">
              <a-input :placeholder="$t('manuManagement.deposit')" v-decorator.trim="[ 'discountMoney' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-if="showAdvanceIn">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.receivedBalance')" :data-title="$t('manuManagement.receivedBalance')"
                         :data-intro="$t('manuManagement.receivedBalance')">
              <a-input style="width:185px;" :placeholder="$t('popup.pleaseThisPayment')" v-decorator.trim="[ 'balance' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          
          <a-col :lg="6" :md="12" :sm="24" v-if="showAdvanceIn">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.substractReceivedAmount')" :data-title="$t('manuManagement.substractReceivedAmount')"
                         :data-intro="$t('manuManagement.substractReceivedAmount')">
              <a-input @input="custom10Change" style="width:185px;" :placeholder="$t('popup.pleaseThisPayment')" v-decorator.trim="[ 'custom10',validatorRules.custom10 ]"/>
            </a-form-item>
          </a-col>
          
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.currentCollection')">
              <a-input style="width:185px;" :placeholder="$t('inPrint.currentCollection')" v-decorator.trim="[ 'changeAmount' ]"/>
            </a-form-item>
          </a-col>
          
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.currentCollection')">
              <a-input style="width:185px;" :placeholder="$t('inPrint.currentCollection')" v-decorator.trim="[ 'custom9',validatorRules.custom9 ]" @input="amountChange"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.giveChange')">
              <a-input style="width:185px;" :placeholder="$t('popup.giveChange')" v-decorator.trim="[ 'custom8' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')" data-step="10"
              :data-title="$t('inPrint.enclosure')" :data-intro="$t('popup.youUploadPictures')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="bill"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :lg="24" :md="24" :sm="24" v-if="depositReceiptNumberList.length">
            <a-form-item :labelCol="{xs: {span: 24}, lg: {span: 2}}" :wrapperCol="{xs: {span: 24}, lg: {span: 22}}" :label="$t('manuManagement.depositReceiptNumber')">
              <span v-for="(item, index) in depositReceiptNumberList" :key="item"><a @click="openFinancialDetail(item, '预收款单')">{{item}}</a><span style="margin: 0 6px;" v-if="index !== depositReceiptNumberList.length-1">,</span></span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <history-bill-list ref="historyBillListModalForm"></history-bill-list>
    <customer-modal ref="customerModalForm" @ok="findBySelectCus"></customer-modal>
    <FinancialDetail ref="FinancialDetail"></FinancialDetail>
    <BillDetail ref="BillDetail"></BillDetail>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import ManyAccountModal from '@/views/bill/dialog/ManyAccountModal'
import LinkBillList from '@/views/bill/dialog/LinkBillList'
import VendorModal from '@/views/system/modules/VendorModal'
import AccountModal from '@/views/system/modules/AccountModal'
import HistoryBillList from '@/views/bill/dialog/HistoryBillList'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { BillModalMixin } from '@/views/bill/mixins/BillModalMixin'
import { getCurrentSystemConfig, findBySelectCus,getAccount,getAccountInfo } from '@/api/api'
import CustomerModal from '@/views/system/modules/CustomerModal'
import { getMpListShort, changeListFmtMinus, handleIntroJs,getNowFormatDateTime } from "@/utils/util"
import FinancialDetail from '@views/financial/dialog/FinancialDetail'
import BillDetail from '@views/bill/dialog/BillDetail'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import { getAction } from '@/api/manage'
export default {
  name: "FactoryMoneyInModal",
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    ManyAccountModal,
    LinkBillList,
    VendorModal,
    AccountModal,
    HistoryBillList,
    FinancialDetail,
    BillDetail,
    JUpload,
    JDate,
    CustomerModal,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    }
  },
  data() {
    return {
      title: this.$t('setailManagement.operation'),
      width: '1600px',
      showAdvanceIn:false,
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      supList: [],
      depotList: [],
      operTimeStr: '',
      prefixNo: 'ZFSK',
      fileList: [],
      rowCanEdit: true,
      purchaseBySaleFlag: true,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
      discountMoney: 0,
      depositReceiptNumberList: [],
      refKeys: ['materialDataTable',],
      tableKeys: ['materialDataTable',],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          { title: this.$t('commodityManagement.delete'), width: '3%', key: 'delete', type: 'slot' },
          { title: this.$t('defaultTranslate.lineNumber'), key: 'rowIndex', width: '4%', type: 'slot' },
          { title: this.$t('manuManagement.documentNo'), key: 'defaultNumber', width: '14%', type: FormTypes.slot, readonly: true },
          
          { title: this.$t('otherJS.receiptdate'), key: 'operTimeStr', width: '10%', type: FormTypes.date, readonly: true },
          { title: this.$t('otherJS.receiptdate'), key: 'billNumber', width: '10%', type: FormTypes.hidden, readonly: true },
          // { title: this.$t('purchasingManagement.invoicedate'), key: 'exchangeTime', width: '8%', type: FormTypes.date},
          // {
          //   title: this.$t('purchasingManagement.invoicenumber'), key: 'invoiceNo', width: '12%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter') + '${title}',
          //   validateRules: [{ required: true, message: '${title}' + this.$t('inPrint.cannotTe') }]
          // },
          { title: this.$t('financialManagement.orderAmount'), key: 'needDebt', width: '10%',readonly: true, type: FormTypes.inputNumber, placeholder: this.$t('inPrint.pleaseTnter') + '${title}',disabled:true },
          { title: this.$t('financialManagement.receivedAmount'), key: 'finishDebt', width: '10%',readonly: true, type: FormTypes.inputNumber, placeholder: this.$t('inPrint.pleaseTnter') + '${title}' ,disabled:true},
          { title: this.$t('purchasingManagement.discountamount'), key: 'discountAmount', width: '10%',readonly:true,type: FormTypes.inputNumber, placeholder: this.$t('inPrint.pleaseTnter') + '${title}' },
          { title: this.$t('financialManagement.amountCollected'), key: 'eachAmount', width: '10%',statistics: true, type: FormTypes.inputNumber, placeholder: this.$t('inPrint.pleaseTnter') + '${title}' ,
            validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') },
                // {
                //   pattern: /^\+?[1-9][0-9]*$/,
                //   message: '${title}' + this.$t('inPrint.GreaterThan_0')
                // },
                {handler:this.validateCheckNumber, message: '${title}' }
              ],
            }, 
          
        ]
      },
      confirmLoading: false,
      validatorRules: {
        accountId: {
          rules: [
            { required: true, message: this.$t('popup.pleaseSelectAccount') + '!' }
          ]
        },
        operTime: {
          rules: [
            { required: true, message: this.$t('popup.pleaseEnterDocumentDate') + '!' }
          ]
        },
        organId: {
          rules: [
            { required: true, message: this.$t('popup.pleaseSupplier') + '!' }
          ]
        },
        custom10: {
          rules: [
            { required: true, message: this.$t('manuManagement.pleaseSubstractAmount') + '!' },
            {validator:this.checkCustom}
          ]
        },
          billNo:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          },
        custom9: {
          rules: [
            { required: true, message: this.$t('popup.pleasePaymentAmount') + '!' },
            {required:true,validator: this.checkChangeAmount}
          ]
        },
          number:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectAssociated') }
            ]
          }
      },
      showCheckNumber: false,
      url: {
        add: '/accountHead/addAccountHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/accountItem/getDetailList'
      }
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        this.showCheckNumber = false
        this.depositReceiptNumberList = []
      }
    }
  },
  created() {
    this.findBySelectCus()
  },
  methods: {
    checkCustom(rule, value, callback) {
      console.log('value :>> ', value);
        this.$nextTick(()=>{
          const form = this.form;
          const balance=form.getFieldValue('balance');
          console.log('balance :>> ', balance);
          let totalPrice = this.materialTable.dataSource.reduce((total,item)=>{
            return total + (+item.eachAmount)
          },0)
          let changeAmount = this.__substraction(totalPrice, this.discountMoney)
          if(changeAmount<0) changeAmount = 0
          console.log('changeAmount :>> ', +changeAmount);
          if (value > balance || value > +changeAmount) {
            this.form.setFieldsValue({
                custom10:balance > changeAmount ? changeAmount : balance,
                // changeAmount:changeAmount - custom10
              })
            callback(this.$t('扣款金额不能大于已付款余额'));
          }
          callback();
        })
      },
    addCustomer () {
      this.$refs.customerModalForm.add()
      this.$refs.customerModalForm.title =
        '新增客户（提醒：如果找不到新添加的客户，请到用户管理检查是否分配了该客户权限）'
      this.$refs.customerModalForm.disableSubmit = false
    },
    findBySelectCus () {
      findBySelectCus().then(res => {
        if (res) {
          this.cusList = res
        }
      })
    },
    // 子tableonchange事件重写，没变更都会计算总金额
    onValueChange(event){
      console.log('555 :>> ', 555);
      const { type, row, column, value, target } = event
      switch (column.key) {
        case 'discountAmount':
        target.setValues([
          {
            rowKey: row.id,
            values: {
              eachAmount:  this.__substraction(row.needDebt , row.discountAmount)
            }
          }
        ])
        break;
      }
      // 触发后重新计算总金额
      this.countDiscountLastMoney();
    },
    // 计算优惠后总金额
    countDiscountLastMoney(){
      this.$refs.materialDataTable.getValues((e,v)=>{
        let arr = v 
        let totalPrice = 0
        arr.forEach(val=>{
          totalPrice  = this.__addition(totalPrice, (val.eachAmount || 0))
        })
        // 定金
        let currentAmount = this.$toDecimal(totalPrice - this.discountMoney)
        console.log('currentAmount :>> ', currentAmount);
        console.log('discountMoney :>> ', this.discountMoney);
        // currentAmount = currentAmount > 0 ? currentAmount : 0
        this.$nextTick(() => {
          this.form.setFieldsValue({
            changeAmount: this.__substraction(totalPrice, this.discountMoney),
            totalPrice,
            custom9: currentAmount,
            custom8:this.$toDecimal(currentAmount + this.discountMoney - totalPrice),
            // discountMoney: this.discountMoney
          })
        })
      })
      
    },
    
    // 校验jedittable 数字大于0
    validateCheckNumber(type, value, row, column, callback, target) {
      let allValues = target.inputValues
      let currentRow = allValues.find(v=>v.id.includes(row.id))
      let needPay = +value - (+currentRow.needDebt -  +currentRow.discountAmount - +currentRow.finishDebt)
      console.log('needPay :>> ', needPay);
      if(+value < 0 && +currentRow.needDebt > 0){
        callback(false,this.$t('otherJS.greaterThan0'))
        return
      }else if(currentRow && currentRow.needDebt && needPay>0){
        callback(false,this.$t('financialManagement.cannotMoreThanOrder'))
      } else{
        callback(true)
      } 
    },
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      this.arrList = []
      this.billStatus = '0'
      this.showAdvanceIn = false
      this.rowCanEdit = true
      this.getSystemConfig()
      // this.changeColumnHide()
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.fileList = []
        this.$nextTick(() => {
          handleIntroJs(this.prefixNo, 1)
          this.$nextTick(() => {
            this.form.setFieldsValue({'billTime': getNowFormatDateTime(),'deduction':0})
          });
        })
      } else {
        if (this.model.linkNumber) {
          this.rowCanEdit = false
          this.materialTable.columns[1].type = FormTypes.normal
        }
        this.model.billTime = this.model.billTimeStr
        if (this.model.accountId == null) {
          this.model.accountId = 0
          this.manyAccountBtnStatus = true
          this.accountIdList = this.model.accountIdList
          this.accountMoneyList = this.model.accountMoneyList
        } else {
          this.manyAccountBtnStatus = false
        }
        
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'organId', 'deliveryMethod', 'billNo','billTime','custom10','deduction','custom9','custom8',
          'arrivalTime', 'operTime', 'number', 'userName', 'creator', 'linkNumber', 'remark',
            'discount', 'discountMoney', 'discountLastMoney', 'accountId', 'changeAmount'))
        });
        this.discountMoney = this.model.discountMoney || 0
        // 加载子表数据
        let params = {
          headerId: this.model.id,
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        }
        let url = this.readOnly ? this.url.detailList : this.url.detailList;
        this.requestSubTableData(url, params, this.materialTable,(res)=>{
          this.materialTable.dataSource =  this.materialTable.dataSource.map(v=>(v.defaultNumber = v.billNumber,v))
        });
        //定金单据编号
        this.depositReceiptNumberList = this.model.custom2 && this.model.custom2.split(',') || []
      }
      //复制新增单据-初始化单号和日期
      if (this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      
      this.initSupplier()
      this.initAccount()
      this.initDepot()
      
    },
    
    checkChangeAmount(rule, value, callback){
        // 定金
        const table = this.$refs[this.refKeys[0]]
        table.getValues((err,v)=>{
          let totalPrice = v.reduce((total,item)=>{
                return total + (+item.eachAmount)
              },0)
          let discountMoney  = this.form.getFieldValue('discountMoney') 
          let custom10 = this.form.getFieldValue('custom10') 
          custom10 = custom10 || 0
          let changeAmount = this.__substraction(totalPrice, this.discountMoney)
          // 实际应付款
          let num =this.$toDecimal(changeAmount - custom10)
          // 当前付款
          let currentAmount = value
          if(currentAmount < +num){
            callback(this.$t('financialManagement.cannotLessThanReceived'));
          }
          callback();
        })
    },
    
    amountChange(e){
      this.form.validateFields(['custom9'])
      // 定金
      let discountMoney  = this.form.getFieldValue('discountMoney') 
      const table = this.$refs[this.refKeys[0]]
      table.getValues((err,v)=>{
      let totalPrice = v.reduce((total,item)=>{
            return total + (+item.eachAmount)
          },0)
      // 预收预付总金额
      let custom10 = this.form.getFieldValue('custom10') 
          custom10 = custom10 || 0
          let changeAmount = this.__substraction(totalPrice, this.discountMoney)
          // 实际应付款
          let num = changeAmount - custom10 > 0 ? ((changeAmount*100 - custom10*100)/100).toFixed(2) : 0
          // 当前付款
          let currentAmount = e.target.value
          let custom8 = +currentAmount - num < 0 || isNaN(+currentAmount - num) ? 0 : (( +currentAmount*100 - num*100)/100).toFixed(2)
          this.form.setFieldsValue({
            custom8: custom8
          })
      })
          
    },
    /**
     * 
     * @param {event} e 
     * 扣除已收款change事件
     */
    custom10Change(e){
      const table = this.$refs[this.refKeys[0]]
      this.form.validateFields(['custom10'])
      table.getValues((err,v)=>{
          let totalPrice = v.reduce((total,item)=>{
            return this.$toDecimal(total + (+item.eachAmount))
          },0)
          console.log('totalPrice :>> ', totalPrice);
          let custom10 = this.form.getFieldValue('custom10') 
          custom10 = custom10 || 0
          let changeAmount = this.__substraction(totalPrice, this.discountMoney)
          let num = changeAmount - custom10 //> 0 ? changeAmount - custom10 : 0
          this.form.setFieldsValue({
            changeAmount: num,
            custom9:num
          })
          this.amountChange({target:{value:num}})
      })
    },
    initAccountInfo(){
      let id = this.form.getFieldValue('organId')
      if(!id){
        this.$message.error(this.$t('popup.pleaseSupplier'))
        return
      }
      getAccountInfo({id:this.form.getFieldValue('organId')}).then((res)=>{
          if(res && res.code === 200) {
            this.form.setFieldsValue({
              balance:res.data.info.advanceIn
            })
            this.custom10Change({})
          }else{
            this.$message.error(res.data.message || res.data )
          }
        })
      },
    selectMoneyChange(e){
      if(e){
        this.showAdvanceIn = true
        this.initAccountInfo()
      }else{
        this.showAdvanceIn = false
        console.log('888 :>> ', 888);
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      billMain.type = '直发收款'
      billMain.subType = '直发收款'
      billMain.defaultNumber = billMain.number
      for (let item of detailArr) {
        totalPrice += item.allPrice - 0
      }
      if (billMain.accountId === 0) {
        billMain.accountId = ''
      }
      this.accountMoneyList = changeListFmtMinus(this.accountMoneyList)
      billMain.accountIdList = this.accountIdList.length > 0 ? JSON.stringify(this.accountIdList) : ""
      billMain.accountMoneyList = this.accountMoneyList.length > 0 ? JSON.stringify(this.accountMoneyList) : ""
      if (this.fileList && this.fileList.length > 0) {
        billMain.fileName = this.fileList
      } else {
        billMain.fileName = ''
      }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.status = this.billStatus
      billMain.custom2 = this.depositReceiptNumberList.join(',')
      let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
      return {
        info: JSON.stringify(billMain),
        attachment: fileList,
        rows: JSON.stringify(detailArr),
      }
    },
    handleHistoryBillList() {
      let organId = this.form.getFieldValue('organId')
      this.$refs.historyBillListModalForm.show(this.$t('manuManagement.other'), this.$t('manuManagement.purchaseOrder'), this.$t('manuManagement.supplier'), organId);
      this.$refs.historyBillListModalForm.disableSubmit = false;
    },
    onSearchLinkNumber() {
      let organId = this.form.getFieldValue('organId')
      // this.$refs.linkBillList.show('其它', this.$t('manuManagement.purchaseOrder'), this.$t('warehouseManagement.supplier'), "1,3", organId)
      this.$refs.linkBillList.acceptanceShow('其它', '厂家直发', this.$t('manuManagement.customer'), "2", organId, this.prefixNo)
      this.$refs.linkBillList.title = this.$t('manuManagement.directOrdersFromManufacturers')
    },
    linkBillListOk(selectBillDetailRows, linkNumber, organId) {
      this.rowCanEdit = false
      getAction('/accountHead/getDepositByNumber', { number: linkNumber, payStatus: 3}).then(res => {
        if (res.code == 200) {
          const {data} = res
          if (!isNaN(data.discountMoney)) {
            this.discountMoney = data.discountMoney
            this.form.setFieldsValue({
              discountMoney: this.discountMoney
            })
          }
          if (data.billNo) {
            this.depositReceiptNumberList = data.billNo.split(',')
          }
        }
        // this.materialTable.columns[2].type = FormTypes.select
      if(selectBillDetailRows && selectBillDetailRows.length>0) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'number': linkNumber
          })
        })
        
      // 获取供货商信息计算折扣金额
        
        var endDate = new Date();
        this.getSupplierInfo(organId).then(res=>{
          let info = res.info
           selectBillDetailRows.forEach(v=>{
            var beginDate = new Date(v.operTime);
            var days = (endDate - beginDate) / (1000 * 60 * 60 *24);
            v.needDebt = v.discountLastMoney 
            if(days > info.paymentPeriods){
              // 过期
              v.discountAmount = 0
            }else{
              if(v.needDebt < 0){
                v.discountAmount = 0
              }else{
                v.discountAmount = (v.needDebt * info.discountRate / 100).toFixed(2)
              }
            }
            v.eachAmount = this.$toDecimal(v.needDebt - v.discountAmount - v.finishDebt)
            v.exchangeTime = v.operTimeStr
            v.billNumber = v.number
          })
          this.materialTable.dataSource = selectBillDetailRows
          let totalPrice = selectBillDetailRows.reduce((total,item)=>{
            return this.__addition(total, item.eachAmount)
          },0)
          // 提前付款金额
          let custom10 = info.advanceIn
          let changeAmount = this.__substraction(totalPrice, this.discountMoney)
          if(this.showAdvanceIn){
            if(custom10>changeAmount){
              custom10 = changeAmount
              changeAmount = 0
            }else{
              changeAmount = this.$toDecimal(changeAmount - custom10)
            }
          }
          this.$nextTick(() => {
              this.form.setFieldsValue({
                'changeAmount': changeAmount,
                'custom9': changeAmount,
                'custom10':custom10,
                'custom8':0,
                totalPrice:totalPrice
              })
            });
        })
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'organId': organId
          })
        })
      }



      })
      
    },
    // 获取供货商信息
    getSupplierInfo(id){
      return new Promise((resolve,reject)=>{
        getAction('supplier/info',{id:id}).then(res=>{
          if(res.code == 200){
            resolve(res.data)
          }else{
            reject()
          }
        })
      })
    },
    getSystemConfig() {
      getCurrentSystemConfig().then((res) => {
        console.log(res);
        if (res.code === 200 && res.data) {
          this.purchaseBySaleFlag = res.data.purchaseBySaleFlag === '1' ? true : false
        }
      })
    },
    onSelectAccount (value) {
      const item = this.accountList.find(item => item.id === value)
      const IS_CHECK_PAY = '1'
      if (value && item.type && item.type.toString() === IS_CHECK_PAY) {
        this.showCheckNumber = true
      } else {
        this.showCheckNumber = false
      }
    },
    initAccount () {
      getAccount().then(res => {
        if (res && res.code === 200) {
          this.accountList = res.data.accountList
        }
      })
    },
    removeRows (text) {
      this.$refs[this.refKeys[0]].removeRows(text.rowId)
      this.countDiscountLastMoney()
    }
  }
}
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>